<template>
  <custom-dialog
    ref="dialog" title="选择位置" width="600px" class="no-padding-body"
    :show-cancel-button="false" confirm-button-text="确定"
    :before-confirm="beforeConfirm" :on-confirm="afterConfirm"
  >
    <div style="width:100%;height:200px;">
      <el-amap
        ref="amap"
        map-style="amap://styles/macaron"
        :zoom="20"
        :events="mapEvents"
      ></el-amap>
    </div>
  </custom-dialog>
</template>

<script>
import CustomDialog from '@/components/custom-dialog'
import Vue from 'vue'
import VueAMap from '@/plugins/amap'

Vue.use(VueAMap)
export default {
  name: 'index',
  components: { CustomDialog },
  props: {
    value: String,
  },
  data () {
    return {
      map: null,
      mapEvents: {
        init: (map) => {
          this.map = map
        },
        click: (evt) => {
          const { lng, lat } = evt.lnglat
          const lnglat = `${lng},${lat}`
          this.$nextTick(() => {
            this.mark(lnglat)
            this.$emit('input', lnglat)
          })
        }
      },
    }
  },
  methods: {
    open () {
      const lnglat = this.value
      this.$nextTick(() => {
        this.$refs.dialog.open()
        setTimeout(() => {
          this.mark(lnglat)
          if (lnglat) {
            this.map.setFitView()
          }
        }, 20)
      })
    },
    beforeConfirm () {
      return true
    },
    afterConfirm (close) {
      return new Promise((resolve) => {
        resolve()
        this.map.clearMap()
        this.$emit('change', this.value)
        close()
      })
    },
    mark (lnglat) {
      const AMap = window.AMap
      lnglat = (lnglat || '').split(',')
      if (AMap && lnglat.length === 2) {
        const marker = new AMap.Marker({
          position: lnglat
        })
        if (this.map) {
          this.map.clearMap()
          this.map.add(marker)
        }
      } else {
        if (this.map) {
          this.map.clearMap()
        }
      }
    },
  },
}
</script>

<style scoped>
.no-padding-body >>> .el-dialog__body {
  padding: 0;
}
</style>
